package com.mbc.web.common.client.ui;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.mbc.web.common.shared.HttpStatus;
import com.mbc.common.entities.Currency;
import com.mbc.common.entities.CurrencyRate;
import com.mbc.common.entities.CurrencyRateDetail;
import com.mbc.web.common.client.ButtonActionType;
import com.mbc.web.common.client.ClientSingleton;
import com.mbc.web.common.client.CommonControllerMgr;
import com.mbc.web.common.client.CommonMessage;
import com.mbc.web.common.client.ViewUtils;
import com.mbc.web.common.client.ui.control.MButton;
import com.mbc.web.common.client.ui.control.MListBox;
import com.mbc.web.common.client.ui.control.MRadioButton;
import com.mbc.web.common.client.ui.control.MTextBox;
import com.mbc.web.common.shared.dto.CurrencyRateViewLoadDTO;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.dom.client.ChangeEvent;

public class FrmCurrencyRate extends Composite {

	@UiField MButton btnSave;
	@UiField MButton btnEdit;
	@UiField MButton btnDelete;
	@UiField MButton btnReset;
	@UiField MButton btnNew;
	//MBC(6/8/2014)
	@UiField MButton btnList;
	//MBC End
	@UiField MButton btnBack;
	@UiField MTextBox txtRateCode;
	@UiField MTextBox txtDescription;
	@UiField MListBox listSourceCurrency;
	@UiField MListBox listConvertCurrency;
	@UiField MTextBox txtRate;
	@UiField MRadioButton rdoDivide;
	@UiField MRadioButton rdoMultiply;
	
	private long currencyRateId;
	private CurrencyRate currencyRate;
	private byte action_type;
	
	private static FrmCurrencyRateUiBinder uiBinder = GWT
			.create(FrmCurrencyRateUiBinder.class);

	interface FrmCurrencyRateUiBinder extends UiBinder<Widget, FrmCurrencyRate> {
	}

	public FrmCurrencyRate() {
		initWidget(uiBinder.createAndBindUi(this));
		
		initialize();
	}
	
	public FrmCurrencyRate(CurrencyRate currencyRate){
		initWidget(uiBinder.createAndBindUi(this));
		this.currencyRate = currencyRate;
		initialize();
	}

	private void initialize(){
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			
			@Override
			public void execute() {
				txtDescription.setFocus(true);
			}
		});
		CommonControllerMgr.getCurrencyRateViewLoadDTO(getCurrencyRateViewLoadDTOCallback());
	}
	
	private AsyncCallback<CurrencyRateViewLoadDTO> getCurrencyRateViewLoadDTOCallback(){
		return new AsyncCallback<CurrencyRateViewLoadDTO>() {
			
			@Override
			public void onSuccess(CurrencyRateViewLoadDTO result) {
				if(result.getHttpStatus() == HttpStatus.OK){
					for (Currency l_Currency : result.getCurrencyList()) {
						listConvertCurrency.addItem(l_Currency.getCurrencyCode(), String.valueOf(l_Currency.getCurrencyId()));
						listSourceCurrency.addItem(l_Currency.getCurrencyCode(), String.valueOf(l_Currency.getCurrencyId()));
					}
					txtRateCode.setText(getRateCode());
				}
				
				if(currencyRate != null){
					bindControls(currencyRate);
					enableControls(false);
					btnSave.setEnabled(false);
					btnEdit.setEnabled(true);
					btnDelete.setEnabled(true);
					btnReset.setEnabled(false);
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		};
	}
	
	private void enableControls(boolean enabled){
		txtDescription.setEnabled(enabled);
		listSourceCurrency.setEnabled(enabled);
		listConvertCurrency.setEnabled(enabled);
		rdoDivide.setEnabled(enabled);
		rdoMultiply.setEnabled(enabled);
		txtRate.setEnabled(enabled);
	}
	
	private native void jsClear()/*-{
		$wnd.$("input").val("");
		$wnd.$("select").prop('selectedIndex','0');
	}-*/;
	
	private void clear(){
		jsClear();
		ViewUtils.clearRequiredNotifications();
		currencyRate = null;
		currencyRateId = 0;
	}
	
	private void bindControls(CurrencyRate currencyRate){
		currencyRateId = currencyRate.getCurrencyRateId();
		txtRateCode.setText(currencyRate.getCurrencyRateCode());
		txtDescription.setText(currencyRate.getDescription());
		txtRate.setText(String.valueOf(currencyRate.getCurrencyRateDetail().getRate()));
		for (int i = 0; i < listSourceCurrency.getItemCount(); i++) {
			if(Long.parseLong(listSourceCurrency.getValue(i)) == currencyRate.getSourceCurrencyId()){
				listSourceCurrency.setSelectedIndex(i);
				break;
			}
		}
		for (int i = 0; i < listConvertCurrency.getItemCount(); i++) {
			if(Long.parseLong(listConvertCurrency.getValue(i)) == currencyRate.getConvertCurrencyId()){
				listConvertCurrency.setSelectedIndex(i);
				break;
			}
		}
		if(currencyRate.getRoper().equals("M")){
			rdoMultiply.setValue(true);
			rdoDivide.setValue(false);
		}
		else{
			rdoMultiply.setValue(false);
			rdoDivide.setValue(true);
		}
	}
	
	private CurrencyRate bindCurrencyRate(){
		CurrencyRate l_CurrencyRate = new CurrencyRate();
		l_CurrencyRate.setCurrencyRateId(currencyRateId);
		l_CurrencyRate.setCurrencyRateCode(txtRateCode.getText());
		l_CurrencyRate.setDescription(txtDescription.getText());
		l_CurrencyRate.setSourceCurrencyId(Long.parseLong(listSourceCurrency.getValue(listSourceCurrency.getSelectedIndex())));
		l_CurrencyRate.setConvertCurrencyId(Long.parseLong(listConvertCurrency.getValue(listConvertCurrency.getSelectedIndex())));
		l_CurrencyRate.setRoper(rdoMultiply.getValue() ? "M" : "D");
		
		CurrencyRateDetail l_detail = new CurrencyRateDetail();
		l_detail.seteDateTime(new Date());
		l_detail.setRate(Double.parseDouble(txtRate.getText()));
		l_CurrencyRate.setCurrencyRateDetail(l_detail);
		
		return l_CurrencyRate;
	}
	
	private AsyncCallback<Integer> actionCallback()
	{
		return new AsyncCallback<Integer>() {
			
			@Override
			public void onSuccess(Integer result) {
				ViewUtils.stopAjaxLoader();
				if(result == HttpStatus.OK){
					switch (action_type) {
					case ButtonActionType.action_save:
						ViewUtils.showSuccessMessage(CommonMessage.saved_message);
						ClientSingleton.changeView(new SearchCurrencyRate(txtRateCode.getText(), SearchCurrencyRate.SAVE));
						break;
					case ButtonActionType.action_delete:
						ViewUtils.showSuccessMessage(CommonMessage.deleted_message);
						ClientSingleton.changeView(new SearchCurrencyRate(txtRateCode.getText(), SearchCurrencyRate.DELETE));
						break;
					}
				}
				else{
					switch (result) {
					case HttpStatus.INTERNAL_SERVER_ERROR:
						ViewUtils.showErrorMessage(CommonMessage.internal_server_error_message);
						break;
					case HttpStatus.BAD_REQUEST:
						ViewUtils.showErrorMessage(CommonMessage.getAlreadyExistedMessage("Rate Code(" + txtRateCode.getText() + ")"));
						break;
					case HttpStatus.FORBIDDEN:
						ViewUtils.showErrorMessage(CommonMessage.getDataCannotDeleteMessage("Rate Code(" + txtRateCode.getText() + ")"));
						break;
					}
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		};
	}
	
	@UiHandler("btnNew")
	void onBtnNewClick(ClickEvent event) {
		clear();
		
		enableControls(true);
		
		txtDescription.setFocus(true);
		btnSave.setEnabled(true);
		btnEdit.setEnabled(false);
		btnDelete.setEnabled(false);
		btnReset.setEnabled(false);
	}
	
	private boolean isValid(){
		ViewUtils.closeMessageBox();
		if(!ViewUtils.isValidate())
			return false;
		if(listConvertCurrency.getSelectedIndex() == listSourceCurrency.getSelectedIndex()){
			ViewUtils.showErrorMessage("Convert and Source currencies should not be the same.");
			return false;
		}
		return true;
	}
	
	@UiHandler("btnSave")
	void onBtnSaveClick(ClickEvent event) {
		if(isValid()){
			action_type = ButtonActionType.action_save;
			ViewUtils.startAjaxLoader(CommonMessage.saving_message);
			if(currencyRateId == 0)
				CommonControllerMgr.createCurrencyRate(bindCurrencyRate(), actionCallback());
			else
				CommonControllerMgr.updateCurrencyRate(bindCurrencyRate(), actionCallback());
		}
	}
	
	@UiHandler("btnEdit")
	void onBtnEditClick(ClickEvent event) {
		if(currencyRateId != 0){
			btnReset.setEnabled(true);
			btnSave.setEnabled(true);
			btnEdit.setEnabled(false);
			btnNew.setEnabled(false);
			enableControls(true);
			txtDescription.setFocus(true);
			txtRateCode.setEnabled(false);
			listConvertCurrency.setEnabled(false);
			listSourceCurrency.setEnabled(false);
		}
	}
	
	@UiHandler("btnDelete")
	void onBtnDeleteClick(ClickEvent event) {
		if(currencyRateId != 0)
		{
			ViewUtils.showConfirm(CommonMessage.delete_confirm_message, new CloseHandler<PopupPanel>() {
				
				@Override
				public void onClose(CloseEvent<PopupPanel> event) {
					if(ViewUtils.isAlertYes()){
						action_type = ButtonActionType.action_delete;
						ViewUtils.startAjaxLoader(CommonMessage.deleting_message);
						CommonControllerMgr.deleteCurrencyRate(currencyRateId, actionCallback());
					}
				}
			});
		}
	}
	
	@UiHandler("btnReset")
	void onBtnResetClick(ClickEvent event) {
		bindControls(currencyRate);
		enableControls(false);
		btnReset.setEnabled(false);
		btnSave.setEnabled(false);
		btnEdit.setEnabled(true);
		btnNew.setEnabled(true);
	}
	//MBC(6/8/2014)
	@UiHandler("btnList")
	void onBtnListClick(ClickEvent event) {
		ClientSingleton.changeView(new FrmCurrencyRateRpt());
	}
	//MBC End
	@UiHandler("btnBack")
	void onBtnBackClick(ClickEvent event) {
		ClientSingleton.changeView(new SearchCurrencyRate());
	}
	
	@UiHandler("listSourceCurrency")
	void onListSourceCurrencyChange(ChangeEvent event) {
		txtRateCode.setText(getRateCode());
	}
	
	@UiHandler("listConvertCurrency")
	void onListConvertCurrencyChange(ChangeEvent event) {
		txtRateCode.setText(getRateCode());
	}
	
	private String getRateCode(){
		String l_s = listSourceCurrency.getItemText(listSourceCurrency.getSelectedIndex());
		String l_d = listConvertCurrency.getItemText(listConvertCurrency.getSelectedIndex());
		return l_s + l_d;
	}
}
